package com.yuanqunsoft.alimigration.dao.impl;

import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.yuanqunsoft.alimigration.dao.IModuleDao;
import com.yuanqunsoft.alimigration.model.Application;
import com.yuanqunsoft.alimigration.model.Module;
import com.yuanqunsoft.alimigration.model.Report;

public class ModuleDaoImpl extends HibernateDaoSupport implements IModuleDao {

    @Override
    public void addModule(Module instance) {
        try {
            this.getHibernateTemplate().saveOrUpdate(instance);

        } catch (RuntimeException re) {
            throw re;

        }
    }

    @Override
    public void deleteModule(Module instance) {
        try {
            this.getHibernateTemplate().delete(instance);
        } catch (RuntimeException re) {
            throw re;
        }
    }

    @Override
    public void renameModule(String modName, Integer modId) {
        try {
            Module instance = (Module) this.getHibernateTemplate().get(Module.class, modId);
            instance.setModName(modName);
            this.getHibernateTemplate().saveOrUpdate(instance);

        } catch (RuntimeException re) {
            throw re;
        }

    }

    @Override
    public void updateModule(Module instance) {
        // TODO Auto-generated method stub
        try {
            this.getHibernateTemplate().update(instance);
        } catch (DataAccessException e) {
            // TODO Auto-generated catch block
            throw e;
        }
    }

    @Override
    public List<Module> findByApplicationId(Integer appId) {
        try {
            String query = "from Module r where r.application.appId=?";
            List<Module> result = getHibernateTemplate().find(query, appId);
            return result;
        } catch (RuntimeException re) {
            throw re;
        }
    }

    @Override
    public void deleteByApplicationId(Integer appId) {
        try{
            List<Module> modules = this.findByApplicationId(appId);
            for(Module mod : modules){
                this.getHibernateTemplate().delete(mod);
            }
        }catch(RuntimeException re){
            throw re;
        }
    }

    @Override
    public Module findById(Integer modId) {
        try {
            Module instance = (Module) getHibernateTemplate().get(Module.class, modId);
            return instance;
        } catch (RuntimeException re) {
            throw re;
        }
    }

}
